package com.cqupt.slewing

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.cqupt.slewing.room.Item
import com.cqupt.slewing.room.ItemViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class FavoritesFragment : Fragment() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var filteredItems: LiveData<List<Item>>
    private lateinit var itemViewModel: ItemViewModel
    private lateinit var myViewModel: MyViewModel
    private lateinit var myAdapter: MyAdapter


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_favorites, container, false)
        recyclerView = view.findViewById(R.id.recyclerView)

        myAdapter = MyAdapter(requireActivity())
        recyclerView.layoutManager =
            LinearLayoutManager(requireActivity(), LinearLayoutManager.VERTICAL, false)
        recyclerView.addItemDecoration(
            DividerItemDecoration(
                requireActivity(),
                DividerItemDecoration.VERTICAL
            )
        )
        recyclerView.adapter = myAdapter
        return view
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onViewStateRestored(savedInstanceState: Bundle?) {
        super.onViewStateRestored(savedInstanceState)
        itemViewModel = ViewModelProvider(requireActivity())[ItemViewModel::class.java]
        myViewModel = ViewModelProvider(requireActivity())[MyViewModel::class.java]
        // 刷新蓝牙信标
        lifecycleScope.launch(Dispatchers.IO) {
            itemViewModel.clear()
            for (item in myViewModel.getAllDevice()){
                itemViewModel.insert(item)
            }
        }

        filteredItems = itemViewModel.getAllItemsLive()
        filteredItems.observe(requireActivity()) {
            val temp: Int = myAdapter.itemCount
            myAdapter.setAllItems(it)
            if (temp != it.size) {
                myAdapter.notifyDataSetChanged()
            }
        }

    }

}